import subprocess
import threading

from flask import Flask, request, render_template, make_response, send_from_directory, redirect, url_for

app = Flask(__name__)
global mutex
mutex = threading.Lock()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get-external-image')
def get_external_image():
    # 确保只提供特定的文件
    return send_from_directory('/mnt/image', 'capture-s.jpg', as_attachment=False)

@app.route('/button-click', methods=['POST'])
def handle_button_click():
    global mutex
    data = request.get_json()
    button_number = data.get('button_number')
    # 处理按钮点击逻辑
    # 定义要运行的Python脚本和参数
    script = 'command.py'
    if button_number == 1:
        mutex.acquire()
        print("led on")
        args = ['LED_ON']
        subprocess.call(['python3', script] + args)
        mutex.release()
    elif button_number == 2:
        mutex.acquire()
        print("led off")
        args = ['LED_OFF']
        subprocess.call(['python3', script] + args)
        mutex.release()
    elif button_number == 3:
        mutex.acquire()
        print("capture")
        # subprocess.call(['rm', '-rf', '/mnt/image/capture-s.jpg'])
        args = ['capture']
        subprocess.call(['python3', script] + args)
        mutex.release()

    return make_response(), 204
    # return jsonify(message=f'按钮 {button_number} 被点击了')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
